﻿using Long.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Long.DAL
{
    public class BaseService<T> where T : BaseEntity,new()
    {
        public virtual async Task<int> InsertAsync(T model)
        {
            var runSql = DB.SqlSugarClient.Insertable<T>(model);
            var row = await runSql.ExecuteCommandAsync();
            return row;
        }

        public virtual async Task<bool> UpdateAsync(T model)
        {
            var runSql = DB.SqlSugarClient.Updateable<T>(model);
            var rows = await runSql.ExecuteCommandAsync();
            return rows > 0;
        }

        public virtual async Task<bool> DeleteAsync(T model)
        {
            var runSql = DB.SqlSugarClient.Deleteable<T>(model);
            var rows = await runSql.ExecuteCommandAsync();
            return rows > 0;
        }

        public virtual async Task<T> GetByOneAsync(Expression<Func<T,bool>> where)
        {
            var runSql = DB.SqlSugarClient.Queryable<T>().Where(where);
            return await runSql.FirstAsync();
        }

        public virtual async Task<List<T>> GetByListAsync(Expression<Func<T,bool>> where)
        {
            var runSql = DB.SqlSugarClient.Queryable<T>().Where(where);
            return await runSql.ToListAsync();
        }

       public virtual async Task<bool> ExistAsync(Expression<Func<T,bool>> where)
        {
            if (where == null)
                throw new ArgumentNullException(nameof(where));

            if (DB.SqlSugarClient == null)
                throw new InvalidOperationException("数据库连接未初始化");

            return await DB.SqlSugarClient.Queryable<T>()
                .Where(where)
                .AnyAsync();
        }
    }
}
